package com.qianke.common.util;

import java.util.Calendar;
import java.util.Date;

public class DateSecondUtil {

    public static Integer currentSecond() {
        return Math.toIntExact(System.currentTimeMillis() / 1000);
    }

    public static Integer getSecond(Date date) {
        if (date == null) return null;
        return Math.toIntExact(date.getTime() / 1000);
    }

    public static Integer getSecond(Calendar calendar) {
        if (calendar == null) return null;
        return Math.toIntExact(calendar.getTimeInMillis() / 1000);
    }

    public static Date getDate(Integer second) {
        return new Date(Long.valueOf(second) * 1000);
    }

    public static Integer getSecondByDay(Integer second) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(second * 1000L);

        return calendar.get(Calendar.HOUR_OF_DAY) * 3600
                + calendar.get(Calendar.MINUTE) * 60
                + calendar.get(Calendar.SECOND);
    }

    public static Integer getNextSunday() {
        Calendar nowCalendar = Calendar.getInstance();
        nowCalendar.add(Calendar.DAY_OF_YEAR, 15 - getWeek(nowCalendar));
        nowCalendar.set(Calendar.HOUR_OF_DAY, 0);
        nowCalendar.set(Calendar.MINUTE, 0);
        nowCalendar.set(Calendar.SECOND, 0);
        nowCalendar.set(Calendar.MILLISECOND, 0);
        return getSecond(nowCalendar);
    }

    public static Integer getDaySecond(Integer second) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(second * 1000L);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return getSecond(calendar);
    }

    public static Integer getNextMonth() {
        Calendar nextMonth = Calendar.getInstance();
        nextMonth.add(Calendar.MONTH, 1);
        return getSecond(nextMonth);
    }

    public static Integer getWeek(Long millisecond) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(millisecond);
        return getWeek(calendar);
    }


    public static Integer getWeek(Integer second) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(second * 1000L);
        return getWeek(calendar);
    }

    public static Integer getWeek(Calendar calendar) {
        int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        return week == 0 ? 7 : week;
    }


}
